package com.tigercel.xiangchengyun.utils;

import android.content.Context;
import android.os.Handler;
import android.os.Message;

import java.util.List;
import java.util.Vector;

public class BaseHandler extends Handler {
    protected Context context;
    /**
     * List<Handler> 维护每个Activity的handler
     */
    private final static List<Handler> handlers = new Vector<Handler>();
    public BaseHandler() {
    }

    public BaseHandler(Callback callback) {
    }

    public BaseHandler(Context context) {
        this.context = context;
    }

    /**
     * 将handler添加到List<Handler>
     */
    public void addSelf(Handler handler) {
        synchronized (handlers) {
            handlers.add(handler);
        }
    }

    /**
     * 将handler从List<Handler>移除
     */
    public boolean removeSelf(Handler handler) {
        synchronized (handlers) {
            return handlers.size() > 0 && handlers.remove(handler);
        }

    }

    /**
     * 将服务发送过来的message发送到各个Activity
     */
    public void sendMsg(Message msg) {
        if (handlers.size() > 0) {
            Message mmsg = Message.obtain();
            synchronized (handlers) {
                for (Handler mHandler : handlers) {
                    mmsg.what = msg.what;
                    mmsg.obj = msg.obj;
                    mHandler.sendMessage(mmsg);
                    mmsg = mHandler.obtainMessage();
                }
            }
        }
    }

    /**
     * 将服务发送过来的message发送到各个Activity
     */
    public void sendProcessMsg(Message msg) {
        if (handlers.size() > 0) {
            synchronized (handlers) {
                for (Handler mHandler : handlers) {
                    Message mmsg = Message.obtain();
                    mmsg.copyFrom(msg);
                    mHandler.sendMessage(mmsg);
                }
            }
        }
    }

    public void clear() {
        synchronized (handlers) {
            handlers.clear();
        }
    }
}
